package lexical.domain;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Codification table class
 * 
 * @author Boghy
 * 
 */
public class CT {
	private String fileName = "ct.txt";
	public static int IDENTIFIER;
	public static int CONSTANT;
	private Pattern identifierPattern = Pattern
			.compile("^[a-zA-Z][a-zA-Z_0-9]{0,7}");
	private Pattern constantPattern = Pattern
			.compile("[+|-]?[1-9][0-9]+|[+|-]?[0-9]|'[a-zA-Z0-9 \\.\\,\\;\\:\\!\\?\\-\\/]'|\"[a-zA-Z0-9 \\.\\,\\;\\:\\!\\?\\-\\/]*\"");
	private Map<String, Integer> map = new HashMap<String, Integer>();

	public CT() {
		try {
			Scanner sc = new Scanner(new FileInputStream(fileName));
			int code = 0;
			while (sc.hasNext()) {
				map.put(sc.next(), code);
				code++;
			}
			sc.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	// public CT() {
	// Properties prop = new Properties();
	// try {
	// prop.load(new FileInputStream(fileName));
	// } catch (IOException e) {
	// e.printStackTrace();
	// System.exit(1);
	// }
	//
	// for (String key : prop.stringPropertyNames()) {
	// String value = prop.getProperty(key);
	// if (key.equals("Constant")) {
	// CONSTANT = Integer.valueOf(value);
	// } else if (key.equals("Identifier")) {
	// IDENTIFIER = Integer.valueOf(value);
	// } else {
	// map.put(key, Integer.valueOf(value));
	// }
	// }
	// }

	/**
	 * 
	 * @param token
	 * @return the code of the token or null if the token is not found
	 */
	public Integer getCode(String token) {
		Integer code;
		code = map.get(token);
		if (code == null)
			if (isIdentifier(token)) {
				code = IDENTIFIER;
			} else if (isConstant(token)) {
				code = CONSTANT;
			}
		return code;
	}

	private boolean matchesPattern(String token, Pattern pattern) {
		Matcher matcher = pattern.matcher(token);
		return matcher.matches();
	}

	private boolean isIdentifier(String token) {
		Matcher matcher = identifierPattern.matcher(token);
		return matcher.matches();
	}

	private boolean isConstant(String token) {
		Matcher matcher = constantPattern.matcher(token);
		return matcher.matches();
	}

}
